<?php

namespace App\Admin\Forms\Service;

use App\Models\Config as Model;
use App\Models\OrderCommission;
use App\Models\ServiceOrder;
use App\Models\ShopUser;
use App\Models\Worker;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class HandleCancel extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
         $res = 0;
         if ($input){
             try {
                 $oid = $input['id'];
                 $state = $input['state'];
                 $money = floatval($input['money']?:0);
                 $order = ServiceOrder::whereId($oid)->first();
                 $amount = floatval($order->amount);
                 if ($state==1){
                     if ($money>$amount){
                         throw new Exception("输入的退回金额不能大于订单金额!");
                     }
                     $order->refund_amount = $money;
                     $order->is_apply = 0;
                     $order->cancel_time = now()->format("Y-m-d H:i:s");
                     $order->status = 4;
                 }elseif ($state==2){
                     $order->is_apply = 0;
                 }
                 $res = $order->save();
             }catch (ModelNotFoundException|Exception $e){
                 return $this->response()->error($e->getMessage());
             }
         }
         return $this->response()->success($res?'保存成功.':'暂无修改.')->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->display("order_id");
        $this->hidden("id");
        $this->display('car.name','客户姓名');
        $this->display('car.phone','客户电话');
        $this->display('amount','订单金额');
        $this->radio("state","审核")->options(['待审核','审核通过','审核拒绝'])->default(0)->when(1,function (){
            $this->decimal("money","退回金额")->help("通过,可设置取消退部分余额 或者留空不填则默认退回全部订单金额");
        });
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        return $this->getDefault();
    }

    protected function getDefault(){
        $oid = $this->payload['oid'];
        $order = ServiceOrder::whereId($oid)->with('user')->first();
        return $order->toArray();
    }
}
